Skip to content

fix: transactions paging using effective order #971

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 17, 2025

Conversation

gfyrag
Copy link
Contributor

@gfyrag gfyrag commented Jun 16, 2025

No description provided.

@gfyrag gfyrag requested a review from a team as a code owner June 16, 2025 10:01
Copy link

coderabbitai bot commented Jun 16, 2025

Walkthrough

The changes introduce a Table field to the ColumnPaginator struct and update its pagination logic to convert pagination IDs to the correct SQL type using table metadata. The paginator is now explicitly bound to the relevant database table in multiple store methods. An end-to-end test is added to verify paginated transaction listing. The Bun ORM dialect is also updated to register ledger-related models.

Changes

File(s) Change Summary
internal/storage/common/paginator_column.go Added Table field to ColumnPaginator, implemented SQL type conversion for pagination IDs, and helper method.
internal/storage/ledger/store.go, internal/storage/system/store.go Set the Table field in paginators to explicitly specify the target database table.
internal/storage/driver/module.go Registered ledger-related models with Bun ORM dialect during FX module setup.
test/e2e/api_transactions_list_test.go Added a test to verify paginated transaction listing using the next page cursor.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API
    participant Store
    participant Paginator
    participant DB

    Client->>API: Request paginated data (with/without cursor)
    API->>Store: Fetch data with pagination options
    Store->>Paginator: Initialize with Table metadata
    Paginator->>Paginator: Convert PaginationID to SQL type
    Paginator->>DB: Query with converted PaginationID
    DB-->>Paginator: Return paginated results
    Paginator-->>Store: Return results
    Store-->>API: Return results
    API-->>Client: Respond with data and next cursor
Loading

Possibly related PRs

Suggested reviewers

  • Dav-14

Poem

Hopping through columns, a table in tow,
The paginator now knows where to go!
With types aligned and tests that run,
The queries leap and pages spun.
Cursor in paw, I bound to the next,
A bunny well-versed in SQL context!
🐇✨


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d32834f and a2a7f3e.

📒 Files selected for processing (5)
  • internal/storage/common/paginator_column.go (4 hunks)
  • internal/storage/driver/module.go (2 hunks)
  • internal/storage/ledger/store.go (2 hunks)
  • internal/storage/system/store.go (1 hunks)
  • test/e2e/api_transactions_list_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • internal/storage/system/store.go
  • internal/storage/ledger/store.go
  • internal/storage/driver/module.go
  • test/e2e/api_transactions_list_test.go
  • internal/storage/common/paginator_column.go
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Commit Unit Tests in branch fix/transactions-paging-using-effective-order
  • Post Copyable Unit Tests in Comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (1)
internal/storage/ledger/store.go (1)

81-84: Same sanity check needed for the "logs" table

Duplicate of the previous comment, applied to the logs paginator.

🧹 Nitpick comments (2)
internal/storage/common/paginator_column.go (1)

72-79: Extend SQL-type handling in convertPaginationIDToSQLType

Only plain timestamp/timestamp without time zone are recognised. Common aliases such as
timestamptz, timestamp with time zone, or dialect-specific names will silently fall through,
sending a *big.Int to the driver and breaking the query.

Consider normalising/strings.HasPrefix checks or a map-based lookup:

-case "timestamp without time zone", "timestamp":
+case "timestamp without time zone", "timestamp", "timestamp with time zone", "timestamptz":
test/e2e/api_transactions_list_test.go (1)

223-237: Strengthen assertion – validate content, not only length

The new test only checks that the second page contains pageSize elements.
As we already pre-computed the expected ordering (page slice in the parent context), we can verify
the actual IDs to protect against subtle off-by-one/ordering regressions.

-It("Should return next elements", func() {
-    Expect(rsp.V2TransactionsCursorResponse.Cursor.Data).To(HaveLen(int(pageSize)))
-})
+It("Should return the expected next page", func() {
+    Expect(rsp.V2TransactionsCursorResponse.Cursor.Data).
+        To(Equal(page[:pageSize]), "cursor did not return the expected transactions")
+})
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3539a1b and 348a7cf.

📒 Files selected for processing (4)
  • internal/storage/common/paginator_column.go (4 hunks)
  • internal/storage/ledger/store.go (2 hunks)
  • internal/storage/system/store.go (1 hunks)
  • test/e2e/api_transactions_list_test.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Tests
  • GitHub Check: Dirty
🔇 Additional comments (2)
internal/storage/ledger/store.go (1)

68-71: Verify that Dialect().Tables().ByName("transactions") returns a non-nil table

ByName returns nil when the table is unknown; this would bubble into the paginator and trip the
nil-checks suggested above. Please add a sanity check (or panic with a descriptive message) during
store initialisation to fail fast rather than at request time.

internal/storage/system/store.go (1)

105-106: Ensure _system.ledgers table metadata is registered

As with the ledger store, confirm Dialect().Tables().ByName("_system.ledgers") is not nil to
avoid late panics when paginating ledgers.

Comment on lines +18 to 19
Table *schema.Table
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Table field can be nil – potential runtime panic

o.Table is dereferenced later (o.Table.FieldMap[...]) without any nil-check.
If any caller forgets (or fails) to set Table, the first paginated request will panic.

Add a defensive check early in Paginate, or at least fail fast with a clear error:

+if o.Table == nil {
+    return nil, fmt.Errorf("column paginator: Table metadata is nil – caller must set it")
+}

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In internal/storage/common/paginator_column.go around lines 18 to 19, the Table
field can be nil but is dereferenced later without a nil-check, risking a
runtime panic. Add a defensive nil-check for o.Table early in the Paginate
method and return a clear error if it is nil to prevent panics and fail fast.

Comment on lines +48 to 52
paginationID := convertPaginationIDToSQLType(
o.Table.FieldMap[paginationColumn].DiscoveredSQLType,
query.PaginationID,
)
if query.Reverse {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Unsafe access to FieldMap – verify column exists

o.Table.FieldMap[paginationColumn] will return nil for an unknown column and the subsequent
.DiscoveredSQLType dereference will panic.
Guard the lookup and surface a proper error instead of crashing:

-field := o.Table.FieldMap[paginationColumn]
-if field == nil {
-    return nil, fmt.Errorf("unknown pagination column %q for table %s", paginationColumn, o.Table.Name)
-}
-paginationID := convertPaginationIDToSQLType(field.DiscoveredSQLType, query.PaginationID)
+field := o.Table.FieldMap[paginationColumn]
+if field == nil {
+    return nil, fmt.Errorf("unknown pagination column %q for table %s", paginationColumn, o.Table.Name)
+}
+paginationID := convertPaginationIDToSQLType(field.DiscoveredSQLType, query.PaginationID)

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In internal/storage/common/paginator_column.go around lines 48 to 52, the code
directly accesses o.Table.FieldMap[paginationColumn] without checking if the key
exists, which can cause a panic if the column is unknown. Add a check to verify
that the paginationColumn key exists in FieldMap before accessing
DiscoveredSQLType. If the key is missing, return or propagate a clear error
indicating the unknown column instead of allowing a nil dereference.

Copy link

codecov bot commented Jun 16, 2025

Codecov Report

Attention: Patch coverage is 96.15385% with 1 line in your changes missing coverage. Please review.

Project coverage is 82.83%. Comparing base (821333e) to head (a2a7f3e).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
internal/storage/common/paginator_column.go 92.85% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #971      +/-   ##
==========================================
- Coverage   82.83%   82.83%   -0.01%     
==========================================
  Files         142      142              
  Lines        8028     8050      +22     
==========================================
+ Hits         6650     6668      +18     
- Misses       1054     1056       +2     
- Partials      324      326       +2     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
internal/storage/driver/module.go (1)

5-5: Avoid ambiguous import alias

Using the short alias ledger for the root internal package makes call-sites inside this file (ledger.Transaction, ledger.Log, …) visually indistinguishable from the domain term ledger that is already pervasive in the codebase (e.g. ledgerstore). Consider a more explicit alias such as ledgermodel or ledgercore to improve readability.

-import (
-    ...
-    ledger "github.com/formancehq/ledger/internal"
+import (
+    ...
+    ledgermodel "github.com/formancehq/ledger/internal"
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 348a7cf and d32834f.

📒 Files selected for processing (1)
  • internal/storage/driver/module.go (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
internal/storage/driver/module.go (3)
internal/storage/ledger/logs.go (1)
  • Log (20-26)
internal/account.go (1)
  • Account (14-24)
internal/moves.go (1)
  • Move (12-24)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Tests
  • GitHub Check: Dirty
🔇 Additional comments (1)
internal/storage/driver/module.go (1)

25-33: Verify registration happens early enough

db.Dialect().Tables().Register(...) is performed in an fx.Invoke.
Invoke hooks run after all constructors (fx.Provide) have been executed.
If any constructor executed earlier instantiates a paginator or another component that looks up table metadata, it will observe an un-registered schema and fail at runtime.

Please double-check the call sequence or move the registration into a small constructor that depends only on *bun.DB, e.g.

fx.Provide(func(db *bun.DB) *bun.DB {
    db.Dialect().Tables().Register(&ledger.Transaction{}, …)
    return db
})

This guarantees the registration is complete before any other Provide that consumes *bun.DB.

@gfyrag gfyrag force-pushed the fix/transactions-paging-using-effective-order branch from d32834f to a2a7f3e Compare June 16, 2025 11:17
@gfyrag gfyrag added this pull request to the merge queue Jun 17, 2025
Merged via the queue into main with commit b36d454 Jun 17, 2025
9 of 10 checks passed
@gfyrag gfyrag deleted the fix/transactions-paging-using-effective-order branch June 17, 2025 09:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants